import java.util.Arrays;

public class MyPriorityQueue {
    public int[] elem;
    public int usedSize;

    public MyPriorityQueue() {
        this.elem = new int[10];
    }

    /**
     * 建堆的时间复杂度：
     *
     * @param array
     */

    public void createHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            this.elem[i] = array[i];
            usedSize++;
        }
        for (int parent = (usedSize - 1 - 1) / 2; parent >= 0; parent--) {
            shiftDown(parent, usedSize);
        }
    }

    /**
     * @param parent   是每棵子树的根节点的下标
     * @param usedSize 是每棵子树调整结束的结束条件
     *                 向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int parent, int usedSize) {
        int child = 2 * parent + 1;
        while (child < usedSize) {
            if (child + 1 < usedSize && elem[child] < elem[child + 1]) {
                child++;
            }
            //child是左右孩子最大值的下标
            //交换child和root
            if (elem[child] > elem[parent]) {
                swap(child, parent);
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }

    private void swap(int child, int parent) {
        int tmp = elem[child];
        elem[child] = elem[parent];
        elem[parent] = tmp;
    }


    /**
     * 入队：仍然要保持是大根堆
     *
     * @param val
     */
    public void push(int val) {
        if (isFull()) {
            this.elem = Arrays.copyOf(elem, elem.length * 2);
        }
        elem[usedSize] = val;
        shiftUp(usedSize);
        usedSize++;
    }

    private void shiftUp(int child) {
        int parent = (child - 1) / 2;
        while (child > 0) {
            if (elem[child] > elem[parent]) {
                swap(child, parent);
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }

    public boolean isFull() {
        return elem.length == usedSize;
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public int poll() {
        int val = this.elem[0];
        swap(0, usedSize);
        usedSize--;
        shiftDown(0, usedSize);
        return val;
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    /**
     * 获取堆顶元素
     *
     * @return
     */
    public int peekHeap() {
        return elem[0];
    }

    public void heapSort() {
        int end = usedSize - 1;
        while (end > 0) {
            swap(0, end);
            shiftDown(0, end);
            end--;
        }
    }
}